package cn.exrick.xboot.modules.your.controller;

import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.your.entity.User;
import cn.exrick.xboot.modules.your.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chenyunxuan
 */
@Slf4j
@RestController("esUserController")
@Api(description = "陪护床管理接口")
@RequestMapping("/xboot/esUser")
@Transactional
public class UserController {

    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<User> get(@PathVariable String id) {

        User user = iUserService.getById(id);
        return new ResultUtil<User>().setData(user);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<User>> getAll() {

        List<User> list = iUserService.list();
        return new ResultUtil<List<User>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<User>> getByPage(@ModelAttribute PageVo page, @ModelAttribute User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (null != user.getMobile()) {
            qw.like("mobile", user.getMobile());
        }
        if (null != user.getUserName()) {
            qw.like("user_name", user.getUserName());
        }
        if (null != user.getWechatName()) {
            qw.like("wechat_name", user.getWechatName());
        }
        IPage<User> data = iUserService.page(PageUtil.initMpPage(page), qw);
        return new ResultUtil<IPage<User>>().setData(data);
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑或更新数据")
    public Result<User> saveOrUpdate(@ModelAttribute User user) {

        if (iUserService.saveOrUpdate(user)) {
            return new ResultUtil<User>().setData(user);
        }
        return new ResultUtil<User>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids) {

        for (String id : ids) {
            iUserService.removeById(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }
}
